import requests
import json
import time

# API基础URL
BASE_URL = "http://localhost:8000/api/v1"

def test_hardware_prediction():
    """
    测试硬件预测API
    """
    print("\n=== 测试硬件故障预测API ===")
    
    url = f"{BASE_URL}/hardware/predict"
    payload = {
        "device_ids": ["ESL-202-001", "ESL-202-002"],
        "predict_horizon": "7d"
    }
    
    try:
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            result = response.json()
            print("预测结果:")
            for pred in result['predictions']:
                print(f"\n设备ID: {pred['device_id']}")
                print(f"  电池故障概率: {pred['battery_failure_prob']:.4f}")
                print(f"  屏幕故障概率: {pred['screen_failure_prob']:.4f}")
                print("  关键特征:")
                for feature in pred['critical_features']:
                    print(f"    - {feature['name']}: {feature['value']}")
        else:
            print(f"请求失败: {response.status_code}")
            print(response.text)
    except Exception as e:
        print(f"调用API时出错: {e}")
        print("提示: 请确保API服务正在运行 (python src/api/server.py)")

def test_software_anomaly():
    """
    测试软件异常检测API
    """
    print("\n=== 测试软件异常检测API ===")
    
    url = f"{BASE_URL}/software/anomaly"
    payload = {
        "device_id": "ESL-202-001",
        "time_window": "24h"
    }
    
    try:
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            result = response.json()
            print(f"异常分数: {result['anomaly_score']:.4f}")
            print("主要触发因素:")
            for trigger in result['top_triggers']:
                if trigger.get('error_code'):
                    print(f"  - 错误码: {trigger['error_code']}, 计数: {trigger['count']}")
                elif trigger.get('metric'):
                    print(f"  - 指标: {trigger['metric']}, 值: {trigger['value']}")
            print(f"推荐操作: {result['recommended_action']}")
        else:
            print(f"请求失败: {response.status_code}")
            print(response.text)
    except Exception as e:
        print(f"调用API时出错: {e}")
        print("提示: 请确保API服务正在运行 (python src/api/server.py)")

def test_ticket_classification():
    """
    测试工单分类API
    """
    print("\n=== 测试工单分类API ===")
    
    url = f"{BASE_URL}/ticket/classify"
    payload = {
        "ticket_id": "T-202310-123",
        "text_keywords": {
            "刷新慢": 0.85,
            "黑屏": 0.42,
            "电池": 0.31
        },
        "customer_segment": "超市",
        "device_age_bucket": "3-6个月"
    }
    
    try:
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            result = response.json()
            classification = result['classification']
            print(f"问题类型: {classification['problem_type']}")
            print(f"置信度: {classification['confidence']:.4f}")
            print(f"推荐部门: {classification['recommended_department']}")
        else:
            print(f"请求失败: {response.status_code}")
            print(response.text)
    except Exception as e:
        print(f"调用API时出错: {e}")
        print("提示: 请确保API服务正在运行 (python src/api/server.py)")

def test_health_check():
    """
    测试健康检查接口
    """
    print("\n=== 测试健康检查API ===")
    
    url = "http://localhost:8000/health"
    
    try:
        response = requests.get(url)
        if response.status_code == 200:
            result = response.json()
            print(f"服务状态: {'健康' if result['status'] == 'healthy' else '异常'}")
            print(f"模型加载状态: {'已加载' if result['models_loaded'] else '未加载'}")
        else:
            print(f"请求失败: {response.status_code}")
    except Exception as e:
        print(f"调用API时出错: {e}")
        print("提示: 请确保API服务正在运行 (python src/api/server.py)")

def main():
    """
    主函数
    """
    print("物联网价签业务LightGBM服务API示例")
    print("=" * 50)
    
    # 测试健康检查
    test_health_check()
    time.sleep(1)
    
    # 测试硬件预测
    test_hardware_prediction()
    time.sleep(1)
    
    # 测试软件异常检测
    test_software_anomaly()
    time.sleep(1)
    
    # 测试工单分类
    test_ticket_classification()
    
    print("\n" + "=" * 50)
    print("所有API测试完成")
    print("注意: 当前使用的是模拟数据，实际部署时将使用真实数据进行预测")


if __name__ == "__main__":
    main()
